﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BusinessObjects.BO_GetObjects;
using BussinessObjects;
using BusinessObjects;
using LibraryO2S;
using System.IO;

public partial class controls_admin_EbooksEdit : Pages_Base
{
    private DataTable objDT;
    protected void Page_Load(object sender, EventArgs e)
    {
        base.removeHGC(divMessage);
        if (!IsPostBack)
        {
            try
            {
                loadSetting();
                base.loadModuleByType(lsbModule, 0);
                if (lsbModule.Items.Count == 0)
                    lsbModule.Items.Add(new ListItem("Chưa có module hot nào", "-1"));
                base.loadCategories(ddlCategories, 3);
                loadData();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally { base.CloseConnection(); }
        }
    }
    private void loadData()
    {
        if (Request["e_id"] == null)
        {
            divMessage.InnerHtml = O2S_Message.Warning("Cảnh Báo", "Bản ghi này không tồn tại hoặc đã bị xóa !");
            return;
        }
        DataTable objDT = BO_EBooks.Search(Convert.ToInt32(Request["e_id"]));
        if (objDT != null && objDT.Rows.Count > 0)
        {
            txtFULL_ARTICLE_TITLE.Text = objDT.Rows[0]["FULL_BOOK_TITLE"].ToString();
            txtFULL_ARTICLE_DESCRIPTION.Text = objDT.Rows[0]["FULL_BOOK_DESCRIPTION"].ToString();
            txtMetaKeyword.Text = objDT.Rows[0]["META_KEYWORD"].ToString();
            txtMetaDescription.Text = objDT.Rows[0]["META_DESCRIPTION"].ToString();
            ddlCategories.SelectedValue = objDT.Rows[0]["CATEGORY_ID"].ToString();
            cboDisplay.Checked = Convert.ToBoolean(objDT.Rows[0]["IS_DISPLAY_ON_HOME_PAGE"]);
            string contain = "-1:";
            if (Request["m_id"] != null)
            {
                if (Request["t"] != null)
                    contain = Request["m_id"].ToString() + ":";
            }
            string sortdisplay = "1";
            string module_id = objDT.Rows[0]["MODULE_ID"].ToString();
            string[] list_module = module_id.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string per_m_id in list_module)
            {
                foreach (ListItem item in lsbModule.Items)
                    if (item.Value.Equals(per_m_id.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[0]))
                        item.Selected = true;
                if (per_m_id.Contains(contain))
                    sortdisplay = per_m_id.Remove(0, contain.Length);
            }
            txtBookCode.Text = objDT.Rows[0]["BOOK_CODE"].ToString();
            txtSortDisplay.Text = sortdisplay;
            fkcContent.Value = objDT.Rows[0]["BOOK_DETAIL"].ToString();
            if (!objDT.Rows[0]["THUMB_IMG"].ToString().Equals(String.Empty))
                divImg.InnerHtml = "<img src='../upload/ebooks/" + objDT.Rows[0]["THUMB_IMG"].ToString() + "' alt='" + objDT.Rows[0]["FULL_BOOK_TITLE"].ToString() + "' height='100' />";
            if (!objDT.Rows[0]["FILE_NAME"].ToString().Equals(String.Empty))
                divFileName.InnerHtml = "<font color='red'>" + objDT.Rows[0]["FILE_NAME"].ToString() + "</font>";
        }
        else
            divMessage.InnerHtml = O2S_Message.Warning("Hệ Thống", "Bản ghi này không tồn tại hoặc đã bị xóa.");
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            int e_id = Convert.ToInt32(Request["e_id"]);
            objDT = BO_EBooks.Search(e_id);
            string filename = objDT.Rows[0]["THUMB_IMG"].ToString();
            string ebook = objDT.Rows[0]["FILE_NAME"].ToString();
            string path = Server.MapPath("~/upload/ebooks/");
            try
            {
                if (fulTHUMB_IMG.HasFile)
                {
                    filename = fulTHUMB_IMG.FileName;
                    int count = 0;
                    while (File.Exists(path + filename))
                    {
                        filename = count + "_" + fulTHUMB_IMG.FileName;
                        count++;
                    }
                    fulTHUMB_IMG.SaveAs(path + filename);
                }
                if (fulFileName.HasFile)
                {
                    ebook = fulFileName.FileName;
                    int count = 0;
                    while (File.Exists(path + ebook))
                    {
                        ebook = count + "_" + fulFileName.FileName;
                        count++;
                    }
                    fulFileName.SaveAs(path + ebook);
                }
            }
            catch (Exception ex)
            {
                divMessage.InnerHtml = O2S_Message.Error("Hệ Thống", "Lỗi ghi file! " + ex.Message);
                return;
            }
            string code = txtBookCode.Text.Trim();
            int c_id = Convert.ToInt32(ddlCategories.SelectedValue);
            int status = 1;
            string title = txtFULL_ARTICLE_TITLE.Text.Trim();
            string full_article_description = txtFULL_ARTICLE_DESCRIPTION.Text.Trim();
            string details = fkcContent.Value;
            string m_key = txtMetaKeyword.Text.Trim();
            string m_desc = txtMetaDescription.Text.Trim();
            bool displayOnHome = cboDisplay.Checked;
            DataTable admin = (DataTable)Session["Admin"];
            string sort_display = txtSortDisplay.Text.Trim();
            string module_id = ";";
            string contain = "-1:";
            if (Request["m_id"] != null)
            {
                if (Request["t"] != null)
                    contain = Request["m_id"].ToString() + ":";
            }
            string old_mid = objDT.Rows[0]["MODULE_ID"].ToString();
            if (!old_mid.Contains(";-1:"))
                old_mid = ";-1:" + sort_display + old_mid;
            string[] perstr = old_mid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string per in perstr)
            {
                string str = per;
                if (per.Contains(contain))
                    str = per.Substring(0, contain.Length) + sort_display;
                module_id += str + ";";
            }
            string strResult = BO_EBooks.Update(e_id, c_id, code,
                 title, title, full_article_description, full_article_description, filename, ebook, details, m_key, m_desc, "", 0,
                    0, displayOnHome, module_id,
                    DateTime.Now, admin.Rows[0]["USER_NAME"].ToString(), DateTime.Now, "", status);
            if (strResult != "0")
                divMessage.InnerHtml = O2S_Message.Success("Thông Báo", "Cập nhật thành công!");
            else
                divMessage.InnerHtml = O2S_Message.Error("Lỗi", "Có lỗi trong quá trình xử lý!");
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally { base.CloseConnection(); }
    }
    private void loadSetting()
    {
        DataTable objDT = BO_Settings.SelectByGroupId(3, 1);
        foreach (DataRow dr in objDT.Rows)
        {
            string value = dr["SETTING_VALUE"].ToString();
            switch (dr["SETTING_KEY"].ToString())
            {
                case "NOTE_CATE":
                    NOTE_CATE.InnerText = value;
                    break;
                case "NOTE_DISPLAY":
                    NOTE_DISPLAY.InnerText = value;
                    break;
                case "NOTE_MODULE":
                    NOTE_MODULE.InnerText = value;
                    break;
                case "NOTE_SORT":
                    NOTE_SORT.InnerText = value;
                    break;
                case "NOTE_TITLE":
                    NOTE_TITLE.InnerText = value;
                    break;
                case "NOTE_DESCRIPT":
                    NOTE_DESCRIPT.InnerText = value;
                    break;
                case "NOTE_URL":
                    NOTE_URL.InnerText = value;
                    break;
            }
        }
    }
}
